package com.yang.core.plugins.monitoring;

import com.yang.core.api.RestClientInterceptor;
import com.yang.core.model.RequestContext;
import com.yang.core.model.ResponseContext;
import com.yang.core.model.ExceptionContext;
import com.yang.core.config.RestClientProperties;
import lombok.extern.slf4j.Slf4j;

/**
 * RestClient监控拦截器
 */
@Slf4j
public class RestClientMonitoringInterceptor implements RestClientInterceptor {

    private final RestClientProperties.Monitoring monitoringConfig;

    public RestClientMonitoringInterceptor(RestClientProperties.Monitoring monitoringConfig) {
        this.monitoringConfig = monitoringConfig;
    }

    @Override
    public void preRequest(RequestContext context) {
        if (monitoringConfig.isLogRequests()) {
            log.info("发送请求: {} {}", context.getMethod(), context.getUrl());
        }
    }

    @Override
    public void postResponse(ResponseContext context) {
        if (monitoringConfig.isLogResponses()) {
            log.info("收到响应: {} {} ({}ms)",
                context.getStatusCode(),
                context.getStatusCode() == 200 ? "OK" : "ERROR",
                context.getResponseTime());
        }
    }

    @Override
    public void onError(ExceptionContext context) {
        if (monitoringConfig.isLogRequests()) {
            log.error("请求失败: {} {} - {}",
                context.getMethod(),
                context.getUrl(),
                context.getException().getMessage());
        }
    }
}